package com.cndw.kungfu.ext;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;

/**
 * xml处理类
 * 
 * 
 * @author <a href="mailto:whz-work@163.com">汪洪州</a>
 * 
 * @since 1.0 Create on 2011-5-30
 */
public class XmlProcesser {

	@SuppressWarnings("unchecked")
	public static <T> List<T> processXml(Class<T> clazz, String file) {
		List<T> list = new ArrayList<T>();

		Element rootElement = loadXML(file).getRootElement();
		if (rootElement.hasContent() && rootElement.hasMixedContent()) {
			Iterator<Element> iterator = rootElement.elementIterator();
			while (iterator.hasNext()) {

				Element element = iterator.next();
				if (element.getNodeType() == Node.ELEMENT_NODE) {

					T target = org.springframework.beans.BeanUtils.instantiate(clazz);
					Iterator<Element> childIterator = element.elementIterator();
					while (childIterator.hasNext()) {
						Element childElement = childIterator.next();

						if (childElement.getNodeType() == Node.ELEMENT_NODE) {
							try {
								BeanUtils.setProperty(target, childElement.getName(), childElement.getTextTrim());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					list.add(target);
				}
			}
		}
		return list;
	}

	/**
	 * 加载xml文件
	 * 
	 * @param file
	 * @return
	 */
	public static Document loadXML(String file) {
		SAXReader reader = new SAXReader();
		try {
			reader.setEncoding("utf8");
			return reader.read(new ClassPathResource(file).getFile());
		} catch (Exception e) {
			e.printStackTrace();
			return DocumentFactory.getInstance().createDocument();
		}
	}
}
